package io.lkt.task.task.async;

import io.lkt.task.bus.mapper.log.PushDetailLogMapper;
import io.lkt.task.bus.model.ArticleInfo;
import io.lkt.task.bus.model.UserBrandInfo;
import io.lkt.task.bus.model.UserInfo;
import io.lkt.task.bus.model.log.PushDetailLog;
import io.lkt.task.bus.service.*;
import io.lkt.task.model.PlatformSysInfo;
import io.lkt.task.util.RedisCacheUtil;
import io.lkt.task.wechat.service.WeixinServiceDL;
import io.lkt.task.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class UploadTempMsgPushAsyncTask {


    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserBrandService userBrandService;

    @Autowired
    private IArticleService iArticleService;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Async("taskExecutor2")
    public void execute(UserInfo user, String profile, Integer headId) {

        List<UserBrandInfo> userBrandInfoList = userBrandService.getUserSubBrandInfo(user.getUserId());

        Integer brandId = -1;
        String brandName = "";
        if (userBrandInfoList != null && userBrandInfoList.size() > 0) {
            brandId = userBrandInfoList.get(0).getBrandId();
        }

        ArticleInfo articleInfo = null;
        if (!brandId.equals(-1)) {
            //获取是否已经设置了品牌
            brandName = Optional.ofNullable(iArticleService.getArticleBrandName(brandId)).orElse("");

            List<ArticleInfo> brandArticles = iArticleService.getToBePushBrandArticleInfo2(user.getUserId(), userBrandInfoList.get(0), 1);
            if (brandArticles != null && brandArticles.size() > 0) {
                articleInfo = brandArticles.get(0);
            }
        } else {
            brandName = "正能量";
            List<ArticleInfo> typeArticles = iArticleService.getArticleInfoByTypeForCreateTime(1, 1);
            if (typeArticles != null && typeArticles.size() > 0) {
                articleInfo = typeArticles.get(0);
            }
        }

        pubExecute(user, profile, headId, brandName, articleInfo);
    }

    //后台发送
    @Async("taskExecutor2")
    public void executeBrandId(UserInfo user, String profile, Integer headId, Integer brandId, Integer articleId) {

        String brandName = "";
        brandName = Optional.ofNullable(iArticleService.getArticleBrandName(brandId)).orElse("");

        ArticleInfo articleInfo = iArticleService.queryArticleInfoByArticleId(articleId);

        pubExecute(user, profile, headId, brandName, articleInfo);
    }

    private void pubExecute(UserInfo user, String profile, Integer headId, String brandName, ArticleInfo articleInfo){
        Integer ret = 2;

        if (articleInfo != null) {

            PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
            // 发送模板消息接口
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    // 接收者openid
                    .toUser(user.getOpenId())
                    // 模板id
                    .templateId(sysGzh.getSysGzh().getGroundingTempId())
                    // 模板跳转链接
                    .url(sysGzh.getFrontDomain() + "pages/article/detail.html?articleId=" + articleInfo.getId()+"&userId="+user.getUserId())
                    .build();

            String firstMsg = "⭕您好，您订阅的【" + brandName + "】有新引流文章上传";

            // 添加模板数据
            templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1", brandName, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword2", articleInfo.getArticleTitle() + "\n", "#FF00FF"))
                    .addData(new WxMpTemplateData("remark", "🔴回复数字【 6 】  加客服领取销售开单秘籍一份\n🔴回复数字【 9 】  获取品牌更多引流爆文视频！", "#FF0000"));

            PushDetailLog pushDetailLog = new PushDetailLog();
            pushDetailLog.setGzhCode(profile);
            pushDetailLog.setUserId(user.getUserId());
            pushDetailLog.setMsgType(14);//日报
            pushDetailLog.setPushTime(new Date());
            pushDetailLog.setHeadId(headId);
            pushDetailLog.setOpenId(user.getOpenId());
            try {
                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
                if (weixinService == null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile, weixinService);
                }
                weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                ret = 0;
                pushDetailLog.setMsg("成功");
            } catch (WxErrorException e) {
                ret = 2;
                pushDetailLog.setMsg(e.getMessage());
            }
            pushDetailLog.setResult(ret);

            if(ret.equals(0)) {
                redisCacheUtil.setCacheObject("UPLOAD_TEMP_MSG_PUSH" + user.getUserId(), 1, 3600*24);///作用：记录发了多少模板消息给这个用户
            }

            pushDetailLogMapper.addPushDetailLog(pushDetailLog);
        }
    }
}
